package conqueror.com.systemupdate.util;

import android.content.Context;
import android.os.Build;
import android.os.PowerManager;
import android.os.RecoverySystem;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by Administrator on 2016/8/16 0016.
 */
public class RecoverUpdateUtil {

    private static RecoverUpdateUtil instance = null;
    private PowerManager powerManager;

    private RecoverUpdateUtil(PowerManager powerManager) {
        this.powerManager = powerManager;
    }

    /**
     * 单利模式
     *
     * @return
     */
    public static RecoverUpdateUtil getInstance(PowerManager powerManager) {
        if (instance == null) {
            synchronized (RecoverUpdateUtil.class) {
                if (instance == null) {
                    return instance = new RecoverUpdateUtil(powerManager);
                }
            }
        }
        return instance;
    }

    private static final String TAG = RecoverUpdateUtil.class.getName();
    private static final File RECOVERY_DIR = new File("/cache/recovery");
    private static final File COMMAND_FILE = new File(RECOVERY_DIR, "command");
    private static final File LOG_FILE = new File(RECOVERY_DIR, "log");
    //  final String filenameArg = "--update_package=/sdcard/update.zip";
    //  final String localeArg = "--locale=zh_CN";

    /**
     * 加压并安装
     *
     * @param context
     */
    public void excuteUpdateZip(Context context) {
        try {
            RecoverySystem.installPackage(context, new File("/sdcard/update.zip"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据压缩包升级系统
     *
     * @param args
     * @throws IOException
     */
    public void bootCommand(String... args) throws IOException {
        RECOVERY_DIR.mkdirs();  // In case we need it
        COMMAND_FILE.delete();  // In case it's not writable
        LOG_FILE.delete();      //删除log文件
        //写文件
        WriteByFdSync(COMMAND_FILE, args);
        Log.d(TAG, "Current build type is: " + Build.TYPE + "\n");
        //读文件
        ReadInAndPrint(COMMAND_FILE);
        //重新启动
        powerManager.reboot("recovery");
        Log.d(TAG, "!!! powerManager.reboot failed !!!\n");
        throw new IOException("Reboot failed (no permissions?)");
    }

    private void WriteByFdSync(File fhandle, String... args) throws FileNotFoundException, IOException {
        FileOutputStream command = new FileOutputStream(fhandle);
        try {
            for (String arg : args) {
                if (!TextUtils.isEmpty(arg)) {
                    Log.d(TAG, "Write command: " + arg + "\n");
                    command.write(arg.getBytes());
                    command.write("\n".getBytes());
                }
            }
            command.getFD().sync();
        } finally {
            command.close();
        }
        return;
    }

    private String ReadInAndPrint(File fhandle) throws FileNotFoundException, IOException {
        FileReader command_read = new FileReader(fhandle);
        char[] data = new char[256];
        int readCnt = 0;
        String Content = "";
        try {
            readCnt = command_read.read(data);
            if (fhandle.exists()) {
                Log.d(TAG, String.format(">>>Ready to Read from File:%s exists <<<\n", fhandle.getAbsolutePath()));
            }
            for (int i = 0; readCnt > 0 && i < readCnt; i++) {
                Content = Content + String.valueOf(data[i]);
            }
            Log.d(TAG, String.format(">>> %d chars,content:%s from Content <<<", readCnt, Content));

            Log.d(TAG, String.format("Checking actions are done from %s\n", fhandle.getName()));
        } finally {
            command_read.close();
        }
        return Content;
    }


}
